import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { logger } from '../../utils/logger';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES, VALIDATION_ERROR_CODES } from '../../utils/errorCodes';
import { PerformanceStatus } from '@prisma/client';

export class PerformanceController extends BaseController {
  // 获取演出列表
  async getPerformances(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, status, date, artistId, search, venue } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};

      if (search) {
        where.OR = [
          { title: { contains: search as string } },
          { description: { contains: search as string } },
        ];
      }

      if (venue) {
        where.venue = {
          name: { contains: venue as string }
        };
      }
      
      if (status) {
        where.status = status;
      }
      
      if (date) {
        const startDate = new Date(date as string);
        const endDate = new Date(startDate);
        endDate.setDate(endDate.getDate() + 1);
        
        where.startTime = {
          gte: startDate,
          lt: endDate
        };
      }
      
      if (artistId) {
        where.artistId = parseInt(artistId as string);
      }

      // 查询演出列表
      const [performances, total] = await Promise.all([
        prisma.performance.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: { startTime: 'asc' },
          include: {
            artist: {
              select: {
                id: true,
                name: true,
                avatar: true,
              }
            },
            venue: {
              select: {
                id: true,
                name: true,
                description: true,
                address: true,
                city: true,
                country: true
              }
            },
            floorRef: {
              select: {
                id: true,
                name: true,
                level: true,
                status: true
              }
            }
          }
        }),
        prisma.performance.count({ where })
      ]);

      ResponseUtils.paginated(res, performances, total, pageNum, limitNum, '获取演出列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取演出详情
  async getPerformance(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const performanceId = parseInt(id);

      if (isNaN(performanceId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的演出ID');
        return;
      }

      const performance = await prisma.performance.findUnique({
        where: { id: performanceId },
        include: {
          venue: {
            select: {
              id: true,
              name: true,
              description: true,
              address: true,
              city: true,
              country: true
            }
          },
          floorRef: {
            select: {
              id: true,
              name: true,
              level: true,
              status: true
            }
          },
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true,
              description: true,
            }
          }
        }
      });

      if (!performance) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.PERFORMANCE_NOT_FOUND, '演出不存在');
        return;
      }

      ResponseUtils.success(res, performance, '获取演出详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 创建演出
  async createPerformance(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { title, description, venueId, floorId, startTime, endTime, maxCapacity, artistId, status } = req.body;

      if (!title || !venueId || !startTime || !endTime || !artistId) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '缺少必要字段');
        return;
      }

      const start = new Date(startTime);
      const end = new Date(endTime);
      
      if (start >= end) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_VALUE_ERROR, '开始时间必须早于结束时间');
        return;
      }

      // 检查时间冲突
      const conflictingPerformance = await prisma.performance.findFirst({
        where: {
          venueId: parseInt(venueId),
          OR: [
            {
              startTime: { lte: start },
              endTime: { gt: start }
            },
            {
              startTime: { lt: end },
              endTime: { gte: end }
            },
            {
              startTime: { gte: start },
              endTime: { lte: end }
            }
          ]
        }
      });

      if (conflictingPerformance) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.OPERATION_NOT_ALLOWED, '该场地在指定时间段已有演出安排');
        return;
      }

      const performance = await prisma.performance.create({
        data: {
          artistId: parseInt(artistId),
          title,
          description,
          venueId: parseInt(venueId),
          floorId: floorId ? parseInt(floorId) : null,
          startTime: start,
          endTime: end,
          maxCapacity: maxCapacity ? parseInt(maxCapacity) : null,
          status: status as PerformanceStatus
        },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          },
          venue: {
            select: {
              id: true,
              name: true,
              description: true,
              address: true,
              city: true,
              country: true
            }
          }
        }
      });

      logger.info(`演出创建成功: ${performance.title} (ID: ${performance.id})`);
      ResponseUtils.created(res, performance, '创建演出成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新演出信息
  async updatePerformance(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const performanceId = parseInt(id);
        const { title, description, venueId, floorId, startTime, endTime, maxCapacity, status } = req.body;

      if (isNaN(performanceId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的演出ID');
        return;
      }

      // 检查演出是否存在
      const existingPerformance = await prisma.performance.findUnique({
        where: { id: performanceId }
      });

      if (!existingPerformance) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.PERFORMANCE_NOT_FOUND, '演出不存在');
        return;
      }

      // 验证时间逻辑
      if (startTime && endTime) {
        const start = new Date(startTime);
        const end = new Date(endTime);
        
        if (start >= end) {
          ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_VALUE_ERROR, '开始时间必须早于结束时间');
          return;
        }

        // 检查时间冲突（排除当前演出）
        const conflictingPerformance = await prisma.performance.findFirst({
          where: {
            id: { not: performanceId },
            venueId: venueId || existingPerformance.venueId,
            OR: [
              {
                startTime: { lte: start },
                endTime: { gt: start }
              },
              {
                startTime: { lt: end },
                endTime: { gte: end }
              },
              {
                startTime: { gte: start },
                endTime: { lte: end }
              }
            ]
          }
        });

        if (conflictingPerformance) {
          ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.OPERATION_NOT_ALLOWED, '该场地在指定时间段已有演出安排');
          return;
        }
      }

      const updateData: any = {};
      if (title !== undefined) updateData.title = title;
      if (description !== undefined) updateData.description = description;
      if (venueId !== undefined) updateData.venueId = parseInt(venueId);
      if (floorId !== undefined) updateData.floorId = floorId ? parseInt(floorId) : null;
      if (startTime !== undefined) updateData.startTime = new Date(startTime);
      if (endTime !== undefined) updateData.endTime = new Date(endTime);
      if (maxCapacity !== undefined) updateData.maxCapacity = maxCapacity ? parseInt(maxCapacity) : null;
      if (status !== undefined) updateData.status = status as PerformanceStatus;

      const updatedPerformance = await prisma.performance.update({
        where: { id: performanceId },
        data: updateData,
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          },
          venue: {
            select: {
              id: true,
              name: true,
              description: true,
              address: true,
              city: true,
              country: true
            }
          }
        }
      });

      logger.info(`演出更新成功: ${updatedPerformance.title} (ID: ${updatedPerformance.id})`);
      ResponseUtils.success(res, updatedPerformance, '更新演出成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除演出
  async deletePerformance(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const performanceId = parseInt(id);

      if (isNaN(performanceId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的演出ID');
        return;
      }

      // 检查演出是否存在
      const existingPerformance = await prisma.performance.findUnique({
        where: { id: performanceId }
      });

      if (!existingPerformance) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.PERFORMANCE_NOT_FOUND, '演出不存在');
        return;
      }

      await prisma.performance.delete({
        where: { id: performanceId }
      });

      logger.info(`演出删除成功: ${existingPerformance.title} (ID: ${performanceId})`);
      ResponseUtils.success(res, null, '删除演出成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取演出统计信息
  async getPerformanceStatistics(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { startDate, endDate } = req.query;
      
      // 构建时间范围
      const dateFilter: any = {};
      if (startDate && endDate) {
        dateFilter.startTime = {
          gte: new Date(startDate as string),
          lte: new Date(endDate as string)
        };
      }

      const [
        totalPerformances,
        scheduledPerformances,
        ongoingPerformances,
        completedPerformances,
        cancelledPerformances,
        venueStats,
        dailyStats
      ] = await Promise.all([
        // 总演出数量
        prisma.performance.count(),
        
        // 已安排演出数量
        prisma.performance.count({
          where: { status: 'SCHEDULED' }
        }),
        
        // 进行中演出数量
        prisma.performance.count({
          where: { status: 'ONGOING' }
        }),
        
        // 已完成演出数量
        prisma.performance.count({
          where: { status: 'COMPLETED' }
        }),
        
        // 已取消演出数量
        prisma.performance.count({
          where: { status: 'CANCELLED' }
        }),
        
        // 场地统计
        prisma.performance.groupBy({
          by: ['venueId'],
          _count: {
            id: true
          },
          orderBy: {
            _count: {
              id: 'desc'
            }
          }
        }),
        
        // 每日演出统计
        prisma.performance.groupBy({
          by: ['startTime'],
          _count: {
            id: true
          },
          where: dateFilter,
          orderBy: {
            startTime: 'asc'
          }
        })
      ]);

      // 获取场馆名称信息
      const venueIds = venueStats.map(stat => stat.venueId);
      const venues = await prisma.venue.findMany({
        where: { id: { in: venueIds } },
        select: { id: true, name: true }
      });

      const venueMap = new Map(venues.map(venue => [venue.id, venue.name]));

      const statistics = {
        overview: {
          totalPerformances,
          scheduledPerformances,
          ongoingPerformances,
          completedPerformances,
          cancelledPerformances
        },
        venueStats: venueStats.map(stat => ({
          venueId: stat.venueId,
          venueName: venueMap.get(stat.venueId) || '未知场馆',
          count: stat._count?.id || 0
        })),
        dailyStats: dailyStats.map(stat => ({
          date: stat.startTime.toISOString().split('T')[0],
          count: stat._count?.id || 0
        }))
      };

      ResponseUtils.success(res, statistics, '获取演出统计信息成功');
    } catch (error) {
      next(error);
    }
  }
}